package com.stars.easyms.base.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.ConfigurableObjectInputStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化 redis缓存对象
 *
 * @author guoguifang
 * @date 2018-10-19 10:07
 * @since 1.0.0
 */
public final class SerializeUtil {

    private static final Logger logger = LoggerFactory.getLogger(SerializeUtil.class);

    public static byte[] serialize(Object obj) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            return bos.toByteArray();
        } catch (Exception e) {
            logger.error("序列化对象失败", e);
        }
        return new byte[0];
    }

    @SuppressWarnings("unchecked")
    public static <T> T unserialize(byte[] bytes) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ConfigurableObjectInputStream(bis, Thread.currentThread().getContextClassLoader());
            return (T) ois.readObject();
        } catch (Exception e) {
            logger.error("反序列化对象失败", e);
        }
        return null;
    }

    private SerializeUtil() {}
}
